package com.palm.platform.controller;

import com.palm.core.util.StringUtil;
import com.palm.platform.domain.Dictionary;

import com.palm.platform.service.CacheDataService;
import org.noear.solon.core.handle.Result;
import com.palm.core.anno.Auth;
import org.noear.solon.annotation.*;
import org.noear.solon.data.annotation.Tran;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* 字典管理
*
* generated by palmboot
**/
@Auth
@Controller
@Mapping("dictionary")
public class DictionaryController{


    @Inject
    CacheDataService cacheDataService;

    @Db
    SqlToyLazyDao dao;

    @Note("新增字典管理")
    @Mapping("add")
    public Result add(Dictionary dictionary){
        if (StringUtil.isEmpty(dictionary.getType())){
            dictionary.setType("dict");
        }
        dictionary.setUpdateTime(new Date());
        dao.save(dictionary);
        //重建字典缓存
        cacheDataService.buildDictCache();
        return Result.succeed();
    }

    @Note("删除字典管理")
    @Mapping("delete")
    @Tran
    public Result delete(List<Dictionary> dictionarys){
        // dao.loadAll(dictionarys);
        if(dictionarys.size()==0){
            return Result.succeed();
        }
        List<Dictionary> toDeletes= dao.loadAll(dictionarys);
        List<Dictionary> subDicts=new ArrayList<>();
        for(Dictionary dict:toDeletes){
            if("dict".equals(dict.getType())){//字典类型级别，需要删除其子级
                subDicts.addAll(dao.findBySql("select * from t_dictionary where `type`=:sn",dict));
            }
        }
        toDeletes.addAll(subDicts);
        dao.deleteAll(toDeletes);
        //重建字典缓存
        cacheDataService.buildDictCache();
        return Result.succeed();
    }

    @Note("更新字典管理")
    @Mapping("save")
    public Result save(Dictionary dictionary){
        dictionary.setUpdateTime(new Date());
        dao.update(dictionary);
        //重建字典缓存
        cacheDataService.buildDictCache();
        return Result.succeed();
    }

    @Note("获取字典管理")
    @Mapping("detail")
    public Result<Dictionary> detail(Dictionary query){
       Dictionary dictionary=dao.load(query);
       return Result.succeed(dictionary);
    }

    @Note("获取字典管理列表")
    @Mapping("list")
    public Result<List<Dictionary>> list(Dictionary query){
        if(StringUtil.isEmpty(query.getType())){
            return Result.succeed(new ArrayList<>());
        }
        List<Dictionary> result = dao.findBySql("select * from t_dictionary where #[and type=:type] #[and ( name like :name or sn like :name)] order by rank",query);
        return Result.succeed(result);
    }

}
